/*
 * Online.cpp
 *
 *  Created on: Jan 2, 2010
 *      Author: evaleto
 */

#include "config.h"
#ifdef CONFIG_WITH_ETHERNET
//#include "wiring.h"
//#include "HardwareSerial.h"

#include "Online.h"
#include "Led.h"
#undef CONFIG_WITH_DEBUG


//
// implementation
//
#ifdef CONFIG_WITH_PROGMEM
#  include <avr/pgmspace.h>
#else
#  undef PROGMEM
#  define PROGMEM
#endif

uint8_t mac[]  = MAK_ADDRESS;
uint8_t ip[]  = LOCAL_IP;
uint8_t remoteServer[]  = SERVER_IP;
uint8_t gateway[] = GATEWAY;
uint8_t subnet[] = SUBNET;



Online::Online(): localClient(remoteServer,80){
  setup();
}

Online::~Online() {
}

bool Online::update(uint8_t header, uint16_t power[], uint8_t sz){
  //Serial.print("online=");Serial.print(header,DEC);Serial.print(":");Serial.println(sz,DEC);
  
  if (header==0 && sz<4)
    return false;
#ifdef CONFIG_WITH_DEBUG
  Serial.println("Connecting...");
#endif  
  int tm=0;//millis();

//try to remove the presetup
  setup();
  if (!localClient.connect()) {
#ifdef CONFIG_WITH_DEBUG
	  Serial.println("connection failed");
#endif
	  Led::flash(CONFIG_LEDERROR);
	  return false;
  }

  //http://www.gelux.ch/index.php?put=121,122,123,124,125,126,127,128,129&type=0&appid=0987654321
#ifdef CONFIG_WITH_DEBUG
  Serial.print("GET /index.php?put=.... ");
#endif  
  localClient.print("GET /index.php?put=");
  for(uint8_t i=0;i<sz;i++){
	  if(i)localClient.print(",");
	  localClient.print(power[i],DEC);
  }
  localClient.print("&type=");
  localClient.print(header,DEC);

  localClient.print("&appid=");
  localClient.print(API_KEY);

  localClient.print(" HTTP/1.1\nHost: www.gelux.ch\n\n");
//  localClient.print(" HTTP/1.1\nHost: www.gelux.ch\nX-ApiKey: ");
//  localClient.print("\n\n");
//  localClient.print("\nUser-Agent: Arduino (powerusage v1.0)");
//  localClient.print("\nConnection: close\n\n");

  

#ifdef CONFIG_WITH_DEBUG
  Serial.print("in ");
  Serial.print(millis()-tm,DEC);
  Serial.println("ms");
#endif

//	while (localClient.available()) {
//		  //checkForResponse();
//	}

  if (!localClient.connected()) {
	  disconnect();
  }



  return true;
}

void Online::setup(){
  reset();
  Client remoteClient(255);
//  delay(10);
}


void Online::reset(){
  Ethernet.begin(mac, ip, gateway, subnet);
  
}

void Online::disconnect(){
  localClient.flush();
  localClient.stop();
  reset();
}
#endif
